package com.hsy.crm.web.service.redis;

import com.hsy.crm.web.domain.entity.PlatformCustomer;
import com.hsy.crm.web.domain.entity.Product;
import com.hsy.crm.web.domain.vo.product.ProductPageVo;
import com.hsy.crm.web.mapper.ProductMapper;
import com.hsy.crm.web.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * redis relation service
 *
 * cache all customer products
 */
@Service
public class RedisService {

    private static String SPLIT = ".";

    private static String REDIS_PREFIT = "crm";

    //product
    private static String REDIS_PRODUCT_PREFIT = "p";

    @Resource(name = "cacheRedisTemplate")
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    ProductMapper productMapper;

    private List<PlatformCustomer> platformCustomers;


    public void pageProduct(ProductPageVo pageVo){

        String key = REDIS_PREFIT+SPLIT+REDIS_PRODUCT_PREFIT+SPLIT+pageVo.getCustomerId();
        String json = redisTemplate.opsForValue().get(key);
        ArrayList<Product> products = JsonUtils.fromJson(json,ArrayList.class);
    }

    public void init(List<PlatformCustomer> platformCustomers){
        this.platformCustomers = platformCustomers;
        initProducts();
    }

    private void initProducts(){
        for ( PlatformCustomer platformCustomer : platformCustomers ){
            String customerId = platformCustomer.getPlatCustomerId();
            ProductPageVo vo = new ProductPageVo();
            vo.setCustomerId(customerId);
            List<Product> products =  productMapper.choseCache(vo);

            String key = REDIS_PREFIT+SPLIT+REDIS_PRODUCT_PREFIT+SPLIT+customerId;
            redisTemplate.opsForValue().set(key,JsonUtils.toJson(products));
        }
    }

}
